var editObj=null,ptable=null,treeGrid=null,tableId='treeTable',layer=null;

layui.config({
    base: basePath+'/layui/lay/modules/'
}).extend({
    treeGrid:'treeGrid'
}).use(['jquery','treeGrid','layer' ], function(){
    var $=layui.jquery;
    treeGrid = layui.treeGrid;//很重要
    layer=layui.layer;
    var form = layui.form;


    ptable=treeGrid.render({
        id:tableId
        ,elem: '#'+tableId
       ,url: basePath+'/function/getFunctionByUserAuth'
       // ,url: basePath+'/'+adminPath+'/jsondata/treeData.json'
       //,url: basePath+'/specialBusiness/test'
        ,cellMinWidth: 120
        ,idField:'id'//必須字段
        ,treeId:'id'//树形id字段名称
        ,treeUpId:'parentId'//树形父id字段名称
        ,treeShowName:'funcName'//以树形式显示的字段
        ,height: 'full-100'
        //,heightRemove:[".copyright",10]//不计算的高度,表格设定的是固定高度，此项不生效
       // ,height:450
        //,width:document.body.clientWidth - 100
        ,isFilter:false
        ,iconOpen:false//是否显示图标【默认显示】
        ,isOpenDefault:false//节点默认是展开还是折叠【默认展开】
        ,loading:true
        ,method:'post'
        ,cols: [[
             {field:'funcName', width:300,  title: '菜单名称',edit:'text',
                 templet:function(d){
                     return '<i class="layui-icon '+d.icon+'">&nbsp;&nbsp;'+ d.funcName+'</i>'
                 }
             }
            ,{field:'funcNo',  title: '编号' ,edit:'text'}
            ,{field:'path', title: 'URL' ,edit:'text'}
            ,{field:'orderNum',  title: '顺序',edit:'text' }
            ,{field:'icon', title: '图标',edit:'text' }
            ,{ title: '权限' ,
                templet:function(d){
                  return  '<a lay-event="fun-add-opt" class="layui-btn layui-btn-xs">配置</a>'
                }
            }
            ,{ title: 'Report' ,
                templet:function(d){
                    return  '<a lay-event="fun-add-rpt" class="layui-btn layui-btn-xs">配置</a>'
                }
            }
            ,{field:'mobile', title: '移动端', templet :"#mobile", unresize: true}
            ,{field:'state', title: '激活', templet :"#fun-state", unresize: true}
            ,{ title: '操作', align:'center'
                ,templet: function(d){
                    var html='';
                    var addBtn='<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="add">添加</a>';

                    var  delBtn='<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>';

                    return addBtn+delBtn;
                }
            }
        ]]
        ,isPage:false
        ,parseData:function (res) {//数据加载后回调
            //console.log(JSON.stringify(res))
            if(res.code != 0){
                layer.msg(res.msg)
            }else{
                res.count = 0
            }
            return res;
        }
        ,onClickRow:function (index, o) {
            //console.log(index,o,"单击！");
        }
        ,onDblClickRow:function (index, o) {
           //console.log(index,o,"双击");
        }
    });

    treeGrid.on('tool('+tableId+')',function (obj) {
        //console.log(obj.event)
        if(obj.event === 'del'){//删除行
            del(obj);
        }else if(obj.event==="add"){//添加行
            add(obj);
        }else if(obj.event === "fun-add-opt"){
            var pdata= obj?obj.data:null;
            var  funcId = pdata.id || ''
            var title = "<i class='layui-icon layui-icon-note'></i>&nbsp;"+pdata.funcName || ""
            //console.log(funcId)
            openFunAddOpt(funcId,title)
        }else if(obj.event === "fun-add-rpt"){
            var pdata= obj?obj.data:null;
            var  funcId = pdata.id || ''
            var title = "<i class='layui-icon layui-icon-note'></i>&nbsp;"+pdata.funcName || ""
            openFuncAddRpt(funcId,title)
        }
    });


    form.on('switch(filter-func-checked)', function(obj){
        //console.log(obj )
        var id = $(obj.elem).attr("_id");
        var field = $(obj.elem).attr("name");
        var value = obj.elem.checked?1:0;
        var checked = obj.elem.checked
        var param = {field:field,value:value,id:id};
        $.ajax(basePath+"/function/functionUpdate",{
            dataType:"json",
            type:"post",
            data:param,
            success:function(rdata){
                //console.log(JSON.stringify(rdata))
                if(rdata.code != 0){
                    obj.elem.checked = !checked
                    form.render("checkbox")
                    layer.msg(rdata.msg)
                }
            }
        });
    });

    //监听单元格编辑
    treeGrid.on('edit('+tableId+')', function(obj){
        var value = obj.value //得到修改后的值
        var field = obj.field; //得到字段
        var data = {field:field,value:value,id:obj.data.id};
        $.ajax(basePath+"/function/functionUpdate",{
            dataType:"json",
            type:"post",
            data:data,
            success:function(rdata){
                //console.log(JSON.stringify(rdata))
                if(rdata.code == 0){
                    //query()
                }else{
                    layer.msg(rdata.msg,function(){
                        query()
                    })
                }
            }
        });
        //layer.msg('[ID: '+ data.id +'] ' + field + ' 字段更改为：'+ value);
    });
});


function del(pObj) {
    //console.log(pObj)
    var param = {}
    var pdata= pObj?pObj.data:null;
    param.pId=pdata?pdata.id:null;

    layer.confirm("删除菜单["+pObj.data.funcName+"],此操作不能恢复!", {icon: 3, title:'提示'},
        function(index){//确定回调

            $.ajax(basePath+"/function/functionUpdate",{
                dataType:"json",
                type:"post",
                data:{flag:"del",id:param.pId },
                success:function(rdata){
                    //console.log(JSON.stringify(rdata))
                    if(rdata.code == 0){
                        pObj.del();
                        //query()
                    }else{
                        layer.msg(rdata.msg)
                    }
                }
            });
            layer.close(index);
        },function (index) {//取消回调
            layer.close(index);
        }
    );
}

//添加
function add(pObj) {
    var param = {}
    var pdata= pObj?pObj.data:null;
    param.pId=pdata?pdata.id:null;
    $.ajax(basePath+"/function/functionUpdate",{
        dataType:"json",
        type:"post",
        data:{parentId:param.pId },
        success:function(rdata){
            //console.log(JSON.stringify(rdata))
            if(rdata.code == 0){
                var newData = rdata.data;
                newData.pId = param.pId ;
                param = newData;
                //console.log(param)
                treeGrid.addRow(tableId,pdata?pdata[treeGrid.config.indexName]+1:0,param);
            }else{
                layer.msg(rdata.msg)
            }
        }
    });
}

function print() {
    console.log(treeGrid.cache[tableId]);
    var loadIndex=layer.msg("对象已打印，按F12，在控制台查看！", {
        time:3000
        ,offset: 'auto'//顶部
        ,shade: 0
    });
}

function openorclose() {
    var map=treeGrid.getDataMap(tableId);
    var o= map['102'];
    treeGrid.treeNodeOpen(tableId,o,!o[treeGrid.config.cols.isOpen]);

}


function openAll() {
    var treedata=treeGrid.getDataTreeList(tableId);
    treeGrid.treeOpenAll(tableId,!treedata[0][treeGrid.config.cols.isOpen]);

}

function getCheckData() {
    var checkStatus = treeGrid.checkStatus(tableId)
        ,data = checkStatus.data;
    layer.alert(JSON.stringify(data));
}
function radioStatus() {
    var data = treeGrid.radioStatus(tableId)
    layer.alert(JSON.stringify(data));
}
function getCheckLength() {
    var checkStatus = treeGrid.checkStatus(tableId)
        ,data = checkStatus.data;
    layer.msg('选中了：'+ data.length + ' 个');
}

function reload() {
    treeGrid.reload(tableId,{
        page:{
            curr:1
        }
    });
}
function query() {
    treeGrid.query(tableId,{
        page:{
            curr:1
        }
        ,where:{
            funcName: function(){return $("#funcName").val()}
        }
    });
}

function test() {
    console.log(treeGrid.cache[tableId],treeGrid.getClass(tableId));


    /*var map=treeGrid.getDataMap(tableId);
     var o= map['102'];
     o.name="更新";
     treeGrid.updateRow(tableId,o);*/
}

function openFunAddOpt(funcId,title){
    layer.open({
        type: 2,
        title:title,
        area: ['40%', '80%'],
        content: "function-add-opt.html?funcId="+funcId//注意，如果str是object，那么需要字符拼接。
    });
}


function openFuncAddRpt(funcId,title){
    layer.open({
        type: 2,
        title:title,
        area:  ['40%', '70%'],
        content: "function-add-rpt.html?funcId="+funcId ,//注意，如果str是object，那么需要字符拼接。
        end:function(){
            query()
        }
    });
}